package com.yuneec.fly.fragments;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Dimension;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckedTextView;

import com.yuneec.fly.R;
import com.yuneec.fly.events.EventBusFactory;
import com.yuneec.fly.events.uiEvent.BindEvent;
import com.yuneec.fly.events.uiEvent.OnResetEvent;
import com.yuneec.fly.events.uiEvent.ProgressEvent;
import com.yuneec.fly.events.uiEvent.ReflushEvent;
import com.yuneec.fly.events.uiEvent.ScanEvent;
import com.yuneec.fly.events.uiEvent.SetCurrentBindedTextEvent;
import com.yuneec.fly.presenters.AbstractBindPresenter;
import com.yuneec.fly.presenters.BindModelPresenter;
import com.yuneec.fly.views.RightImgTextView;
import com.yuneec.fly.views.WrapContentLinearLayoutManager;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;

/**
 * Created by zd.zhang on 2016/7/15.
 */
public class BindModelFragment extends BaseFragment {
    private RecyclerView list;
    public View progressBar;
    protected AbstractBindPresenter presenter;
    private RightImgTextView bind;

    public BindModelFragment() {
        super();
        presenter = newInstancePresemter();
    }

    public AbstractBindPresenter newInstancePresemter() {
        return new BindModelPresenter();
    }

    @Override
    protected int getContentViewResourceId() {
        return R.layout.bind_list;
    }

    @Override
    public void init(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setupView();
        String currentBind = presenter.getCurrentBind();
        if (currentBind != null) {
            bind.setText(currentBind);
            if (bind.getVisibility() != View.VISIBLE) {
                bind.setVisibility(View.VISIBLE);
            }
        }
        presenter.start(currentBind);
        EventBusFactory.getUiBus().register(this);
        EventBusFactory.getUiBus().post(new ScanEvent());
    }

    @Override
    public void onDestroyView() {
        EventBusFactory.getUiBus().unregister(this);
        presenter.stop();
        bind.setVisibility(View.GONE);
        super.onDestroyView();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSetCurrentBindedTextEvent(SetCurrentBindedTextEvent event) {
        if (!TextUtils.isEmpty(event.binded)) {
            bind.setText(event.binded);
            bind.setVisibility(View.VISIBLE);
        } else {
            bind.setVisibility(View.GONE);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void scan(ScanEvent event) {
        progressBar.setVisibility(View.VISIBLE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onProgress(ProgressEvent event) {
        if (event.show) {
            progressBar.setVisibility(View.VISIBLE);
        } else {
            progressBar.setVisibility(View.GONE);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReflush(ReflushEvent event) {
        try {
            String bind = presenter.getCurrentBind();
            if (bind != null) {
                this.bind.setText(bind);
                this.bind.setVisibility(View.VISIBLE);
            } else {
                this.bind.setVisibility(View.GONE);
            }
            if (list != null && list.getAdapter() != null) {
                list.getAdapter().notifyDataSetChanged();
            }
            progressBar.setVisibility(View.GONE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBind(BindEvent event) {
        try {
            if (event.state == BindEvent.STATE_BINDED) {
                if (event.tag != null) {
                    bind.setText(event.tag.toString());
                    bind.setVisibility(View.VISIBLE);
                    if (presenter.removeIndex(presenter.mChecked)) {
                        presenter.mChecked = -1;
                        if (list != null && list.getAdapter() != null) {
                            list.getAdapter().notifyDataSetChanged();
                        }
                    }
                } else {
                    bind.setVisibility(View.GONE);
                }
                presenter.resetState();
                progressBar.setVisibility(View.GONE);
            } else {
                progressBar.setVisibility(View.VISIBLE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReset(OnResetEvent event) {
        if (event != null && event.success) {
            if (bind.getVisibility() != View.GONE)
                bind.setVisibility(View.GONE);
        }
    }

    private void setupView() {
        list = (RecyclerView) selfView.findViewById(R.id.list);
        list.setLayoutManager(new WrapContentLinearLayoutManager(getActivity()));
        list.setAdapter(new ListAdapter(presenter));
        progressBar = selfView.findViewById(R.id.progressBar);
        bind = (RightImgTextView) selfView.findViewById(R.id.bind);
    }

    public static class ListAdapter extends RecyclerView.Adapter<ListItem> {
        public WeakReference<AbstractBindPresenter> presenter;

        public ListAdapter(AbstractBindPresenter presenter) {
            super();
            this.presenter = new WeakReference<AbstractBindPresenter>(presenter);
        }

        @Override
        public ListItem onCreateViewHolder(ViewGroup parent, int viewType) {
            Context context = parent.getContext();
            CheckedTextView tv = new CheckedTextView(context);
            tv.setPadding(5, 15, 5, 15);
            tv.setBackgroundResource(R.drawable.bg_tab);
            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
            RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            tv.setLayoutParams(lp);
            tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, parent.getContext().getResources().getDimension(R.dimen.dp_20));
            Drawable right = context.getResources().getDrawable(R.drawable.bg_select);
            right.setBounds(0, 0, 40, 40);
            tv.setCompoundDrawables(null, null, right, null);
            AbstractBindPresenter p = presenter.get();
            if (p != null) {
                tv.setOnClickListener(p);
            }
            return new ListItem(tv);
        }

        @Override
        public void onBindViewHolder(ListItem holder, int position) {
            AbstractBindPresenter p = presenter.get();
            boolean checked = false;
            if (p != null) {
                holder.tv.setTag(position);
                holder.tv.setText(p.getName(position));
                checked = p.mChecked == position;
            }
            holder.tv.setChecked(checked);
        }

        @Override
        public int getItemCount() {
            AbstractBindPresenter p = presenter.get();
            if (p != null) {
                return p.getSize();
            }
            return 0;
        }
    }

    public static class ListItem extends RecyclerView.ViewHolder {
        public CheckedTextView tv;

        public ListItem(CheckedTextView itemView) {
            super(itemView);
            this.tv = itemView;
        }
    }
}
